import ExcelJS from 'exceljs';
export default class ExcelImport {
  async import({
    tableInstance
  }){
    this._tableInstance = tableInstance
    let result = await this._importFromFileDialog();
    console.log('result', result)
    let records = result.records.map(t=> {
      let item = {...t}
      for(let key in item){
        let val = item[key]
        if(val.richText && Array.isArray(val.richText)){
          item[key] = val.richText.map(t => t.text).join('')
        }
      }
      return item
    })
    console.log('records', records)
    this._tableInstance.updateOption(
      Object.assign({}, this._tableInstance.options, {
        columns: result.columns
      })
    );
    this._tableInstance.setRecords(records);
  }
  static async importExcelToVTableData(file) {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(await file.arrayBuffer());
    const worksheet = workbook.worksheets[0];
    if (!worksheet) {
      throw new Error('Excel 文件无有效工作表');
    }
    const detectedHeaderRows = this.detectHeaderRowCount(worksheet);
    const headerRows = [];
    for (let i = 1; i <= detectedHeaderRows; i++) {
      const row = worksheet.getRow(i);
      headerRows.push(Array.prototype.slice.call(row.values, 1));
    }
    const columns = ExcelImport.buildColumns(headerRows);
    const records = [];
    const dataRows = [];
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber <= detectedHeaderRows) {
        return;
      }
      const cells = Array.prototype.slice.call(row.values, 1);
      dataRows.push(cells);
    });
    // 小文件直接处理
    let rowStart = 0
    let rowEnd = dataRows.length > 100 ? dataRows.length : 100
    for(let i = rowStart; i<rowEnd; i++){
      let cells = dataRows[i]
      const record = {};
      if(cells){
        cells.forEach((cell, j) => {
          record[`col${j}`] = cell;
        });
      }
      records.push(record);
    }
    console.log('columns', columns, 'records', records);
    return { columns, records };
  }
  static buildColumns(headerRows, colStart = 0, colEnd, level = 0) {
    const row = headerRows[level];
    const columns = [];
    colEnd = colEnd ?? row.length;
    let i = colStart;
    while (i < colEnd) {
      const title = String(row[i] || ``);
      let span = 1;
      while (i + span < colEnd && row[i + span] === title) {
        span++;
      }
      if (level < headerRows.length - 1) {
        const subColumns = ExcelImport.buildColumns(headerRows, i, i + span, level + 1);
        if (subColumns.length === 1) {
          columns.push(subColumns[0]);
        } else {
          columns.push({
            title,
            columns: subColumns,
            hideColumnsSubHeader: false
          });
        }
      } else {
        columns.push({
          field: `col${i}`,
          title,
          cellType: 'text',
          headerType: 'text'
        });
      }
      i += span;
    }
    return columns;
  }
  static detectHeaderRowCount(worksheet) {
    let rowIndex = 1;
    let headerRowCount = 1;
    while (true) {
      const row = worksheet.getRow(rowIndex);
      const cells = Array.prototype.slice.call(row.values, 1);
      let hasConsecutive = false;
      for (let i = 1; i < cells.length; i++) {
        if (cells[i] !== undefined && cells[i] !== '' && cells[i] === cells[i - 1]) {
          hasConsecutive = true;
          break;
        }
      }
      if (hasConsecutive) {
        headerRowCount++;
        rowIndex++;
      } else {
        break;
      }
    }
    return headerRowCount;
  }
  /**
   * 获取文件扩展名
   */
  _getFileExtension(filename) {
    const parts = filename.split('.');
    return parts.length > 1 ? parts[parts.length - 1] : '';
  }
  /**
   * 解析Excel文件
   */
  async _parseExcelFile(file){
    return await ExcelImport.importExcelToVTableData(file);
  }
  async _parseFile(file) {
    const fileExtension = this._getFileExtension(file.name).toLowerCase();
    switch (fileExtension) {
      case 'xlsx':
      case 'xls':
        return await this._parseExcelFile(file);
      default:
        throw new Error(`不支持的文件类型: ${fileExtension}`);
    }
  }
  async _importFromFileDialog(){
    return new Promise((resolve, reject) => {
      const input = document.createElement('input');
      input.type = 'file';
      input.style.display = 'none';
      document.body.appendChild(input);
      input.addEventListener('change', async e => {
        try {
          const file = (e.target).files?.[0];
          if (!file) {
            document.body.removeChild(input);
            reject(new Error('未选择文件'));
            return;
          }
          const result = await this._parseFile(file);
          // 清理
          input.value = '';
          document.body.removeChild(input);
          resolve(result);

        }catch (error) {
          document.body.removeChild(input);
          reject(error);
        }
      })
      input.click();
    })
  }
}
